<template>
  <div class="address-form">
    <ZJHeader :title="pageTitle"/>
    <van-form class="" @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            name="receiverName"
            label="收货人"
            placeholder="收货人"
            autocomplete="off"
            maxlength="10"
            v-model="formModel.receiverName"
            :rules="[{ required: true, message: '请填写收货人' }]"
        />
        <van-field
            name="receiverMobile"
            label="手机号码"
            maxlength="11"
            placeholder="手机号码"
            autocomplete="off"
            v-model="formModel.receiverMobile"
            :rules="[
                { required: true, message: '请填写手机号码' },
                { pattern: /^1\d{10}$/, message: '手机号码格式有误' }
            ]"
        />
        <van-field
            is-link
            readonly
            name="receiverArea"
            label="省市区"
            autocomplete="off"
            placeholder="点击选择地址"
            v-model="areaField"
            @click="handleControlPopup"
            :rules="[{ required: true, message: '请选择省市区' }]"
        />
        <van-popup v-model:show="showPicker" position="bottom">
          <van-area
              title="地址选择"
              :area-list="areaList"
              @confirm="handleAreaChoose"
              @cancel="showPicker = false"
          />
        </van-popup>
        <van-field
            label="详细地址"
            name="receiverAddress"
            autocomplete="off"
            placeholder="详细地址"
            maxlength="30"
            type="textarea"
            v-model="formModel.receiverAddress"
            :rules="[{ required: true, message: '请填写详细地址' }]"
        />
      </van-cell-group>
      <div style="margin: 20px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {Toast} from "vant";
import {areaList} from '@vant/area-data';

import ZJHeader from "@/components/ZJHeader/ZJHeader.vue";
import {IAddForm, IAddressDetail, IEditForm} from "@/views/ZJMy/MyAddress/AddressForm/types";
import useMyModule from "@/store/myModule";
import areaJSON from "@/constants/area"
// 初始化所需参数
const route = useRoute()
const router = useRouter()
const myModule = useMyModule()

// 类型处理
const formType = route.query.type
const pageTitle = formType === "add" ? "新增地址" : "修改地址"
const formModel = ref({
  receiverName: "",
  receivePhone: "",
  receiverMobile: "",
  receiverProvince: {
    code: 0,
    name: ""
  },
  receiverCity: {
    code: 0,
    name: ""
  },
  receiverDistrict: {
    code: 0,
    name: ""
  },
  receiverAddress: "",
  receiverDefault: 0
})

// 地址选择器的输入框的值
const areaField = computed(() => {
  const formValue = formModel.value
  // 有省，代表有选地址了
  if (formValue.receiverProvince.code) {
    return `${formValue.receiverProvince.name} ${formValue.receiverCity.name} ${formValue.receiverDistrict.name}`
  }
})

// 地址选择器处理
const showPicker = ref(false)
const handleAreaChoose = (area: any) => {
  formModel.value.receiverProvince = area[0]
  formModel.value.receiverCity = area[1]
  formModel.value.receiverDistrict = area[2]
  showPicker.value = false
}

// 修改地址处理
const addressId = route.query.id as string
const addressDetail = ref<IAddressDetail>()
// 回显
const setupAddressDetail = () => {
  const {
    receiverName,
    receiverMobile,
    receiverAddress,
    receiverDefault,
    receiverProvince,
    receiverCity,
    receiverDistrict
  } = addressDetail.value as IAddressDetail
  const {province_list, city_list, county_list} = areaJSON
  formModel.value.receiverProvince = {
    "code": receiverProvince,
    "name": province_list[receiverProvince]
  }
  formModel.value.receiverCity = {
    "code": receiverCity,
    "name": city_list[receiverCity]
  }
  formModel.value.receiverDistrict = {
    "code": receiverDistrict,
    "name": county_list[receiverDistrict]
  }
  formModel.value.receiverName = receiverName
  formModel.value.receiverAddress = receiverAddress
  formModel.value.receiverMobile = receiverMobile
}
onMounted(async () => {
  if (formType === "edit") {
    const addressInfo = await myModule.getMyAddressAction({
      id: parseInt(addressId)
    })
    if (addressInfo) {
      addressDetail.value = addressInfo as IAddressDetail
      setupAddressDetail()
    } else {
      Toast.fail("查无地址信息")
    }
  }
})

// 提交处理
const onSubmit = async (value: IAddForm | IEditForm) => {
  delete value.receiverArea
  value.receiverProvince = formModel.value.receiverProvince.code
  value.receiverCity = formModel.value.receiverCity.code
  value.receiverDistrict = formModel.value.receiverDistrict.code
  if (formType === "add") {
    const isSuccess = await myModule.addAddressAction(value)
    if (isSuccess) {
      await router.back()
      Toast.success("新增成功")
    }
  } else {
    const submitForm = value as IEditForm
    if (addressDetail.value?.id) {
      submitForm.id = addressDetail.value.id
      const isSuccess = await myModule.editAddressAction({
        submitForm,
        needNavigate: "/my/address/manage?type=edit&id=" + addressDetail.value?.id
      })
      if (isSuccess) {
        await router.back()
        Toast.success("修改成功")
      }
    } else {
      Toast.fail("获取不到地址信息")
    }
  }
}

// 新增修改表单的显示控制
const handleControlPopup = () => {
  showPicker.value = true
}
</script>

<style scoped lang="less">
@import "src/assets/css/variable";
@import "src/assets/css/mixins";

.address-form {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 890;
  background-color: @theme-grey-color;

  .van-form {
    .van-cell-group {
      margin: 0;
    }
  }
}
</style>
